/*
 *   Copyright 2008 Francois Fernandes
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.googlecode.opendoclibrary.internal.impl.fs.meta;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import com.googlecode.opendoclibrary.internal.impl.fs.FilesystemLibrary;
import com.googlecode.opendoclibrary.internal.impl.fs.IFilesystemLibrary;
import com.googlecode.opendoclibrary.library.spi.IDocumentId;
import com.googlecode.opendoclibrary.library.spi.IMetadata;
import com.googlecode.opendoclibrary.library.spi.IMetadataEntry;
import com.googlecode.opendoclibrary.library.spi.IMetadataView;
import com.googlecode.opendoclibrary.library.spi.LibraryException;
import com.googlecode.opendoclibrary.library.spi.RegisteredNamespace;

public class Metadata implements IMetadata
{
    private static final int GENERATOR_VERSION = 1;

    private final Map<String, Map<String, String>> data;

    private final IDocumentId docId;

    private final IFilesystemLibrary fsLibrary;

    private final Map<String, RegisteredNamespace> registeredNamespaces;

    public Metadata( FilesystemLibrary fsLibrary, IDocumentId docId )
    {
        this.fsLibrary = fsLibrary;
        this.docId = docId;
        registeredNamespaces = new HashMap<String, RegisteredNamespace>();
        // register the internal namespaces
        try
        {
            RegisteredNamespace odlNs =
                new RegisteredNamespace( new URI( IMetadata.ODL_INTERNAL_NS ), IMetadata.ODL_INTERNAL_PREFIX );
            RegisteredNamespace odlNsReg =
                new RegisteredNamespace( new URI( IMetadata.ODL_NS_REGISTRY ), IMetadata.ODL_NS_REGISTRY_PREFIX );
            RegisteredNamespace fsLibNs =
                new RegisteredNamespace( new URI( IFilesystemLibrary.FS_LIBRARY_NS ),
                                         IFilesystemLibrary.FS_LIBRARY_NS_PREFIX );
            registeredNamespaces.put( odlNs.getNamespacePrefix(), odlNs );
            registeredNamespaces.put( odlNsReg.getNamespacePrefix(), odlNsReg );
            registeredNamespaces.put( fsLibNs.getNamespacePrefix(), fsLibNs );
        }
        catch ( URISyntaxException e )
        {
            throw new IllegalStateException( "registration of internal namespaces failed", e );
        }

        data = new HashMap<String, Map<String, String>>();
        // add the virtual table
        data.put( IMetadata.ODL_NS_REGISTRY_PREFIX, new VirtualRegisteredNamespacesMap( registeredNamespaces ) );

        // add the version
        putString( IFilesystemLibrary.FS_LIBRARY_NS, IFilesystemLibrary.META_KEY_METADATA_VERSION,
                   Integer.toString( GENERATOR_VERSION ) );
    }

    private void ensureLegalPrefix( String namespacePrefix )
    {
        if ( !registeredNamespaces.containsKey( namespacePrefix ) )
        {
            throw new IllegalArgumentException( "no registered namespace for prefix: " + namespacePrefix );
        }
    }

    Map<String, String> getNsLocal( String namespacePrefix )
    {
        Map<String, String> nsLocal = data.get( namespacePrefix );

        if ( nsLocal == null )
        {
            nsLocal = new HashMap<String, String>();
            data.put( namespacePrefix, nsLocal );
        }
        return nsLocal;
    }

    @Override
    public RegisteredNamespace[] getRegisteredNamespaces()
    {
        Collection<RegisteredNamespace> reg = registeredNamespaces.values();
        return reg.toArray( new RegisteredNamespace[reg.size()] );
    }

    @Override
    public String getString( String namespacePrefix, String key )
    {
        ensureLegalPrefix( namespacePrefix );
        Map<String, String> nsLocal = getNsLocal( namespacePrefix );
        return nsLocal.get( key );
    }

    @Override
    public IMetadataView getView( String namespacePrefix )
    {
        ensureLegalPrefix( namespacePrefix );
        return new View( registeredNamespaces.get( namespacePrefix ), this );
    }

    @Override
    public Iterator<IMetadataEntry> iterator()
    {
        return new MetadataIterator( data );
    }

    @Override
    public void putString( String namespacePrefix, String key, String value )
    {
        ensureLegalPrefix( namespacePrefix );
        getNsLocal( namespacePrefix ).put( key, value );
    }

    @Override
    public void registerNamespace( URI namespaceURI, String namespacePrefix )
    {
        if ( registeredNamespaces.containsKey( namespacePrefix ) )
        {
            throw new IllegalArgumentException( "namespace prefix already registered: " + namespacePrefix );
        }

        try
        {
            for ( RegisteredNamespace rn : registeredNamespaces.values() )
            {
                if ( rn.getNamespaceURI().equals( namespaceURI ) )
                {
                    throw new IllegalArgumentException( "namespace URI already registered: " + namespaceURI );
                }
            }
        }
        catch ( ConcurrentModificationException e )
        {
            // well - retry
            registerNamespace( namespaceURI, namespacePrefix );
        }

        registeredNamespaces.put( namespacePrefix, new RegisteredNamespace( namespaceURI, namespacePrefix ) );
    }

    @Override
    public void save() throws LibraryException
    {

        Properties meta = new Properties();
        for ( Entry<String, Map<String, String>> nsLocal : data.entrySet() )
        {
            String nsPrefix = nsLocal.getKey();

            for ( Entry<String, String> e : nsLocal.getValue().entrySet() )
            {
                meta.setProperty( nsPrefix + ":" + e.getKey(), e.getValue() );
            }
        }

        OutputStream out = fsLibrary.createMetadataOutput( docId );
        try
        {
            meta.store( out, "automatically generated file by opendoclibrary. DO NOT MODIFY!" );
            out.flush();
            out.close();
        }
        catch ( IOException e )
        {
            throw new LibraryException( "unable to save document metadata", e );
        }
    }
}
